package io;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 09 - 23
 * Time: 11:53
 */
//IO案例3 扫描指定目录，并找到名称或者内容中包含指定字符的所有普通文件（不包含目录）
class Demo3 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的指定目录：");
        String path = scanner.nextLine();
        File rootPath = new File(path);
        if(!rootPath.isDirectory()) {
            System.out.println("你输入要扫描的指定目录不合法：");
            return;
        }
        System.out.println("请输入要查找的文件名和文件内容中要包含的指定关键字：");
        String word = scanner.nextLine();
        scanDir(rootPath, word);
    }
    private static void scanDir(File file, String word) throws IOException {
        File[] files = file.listFiles();
        if(files == null) return;
        for (File f : files) {
            if(f.isFile()) {
                if(f.getName().contains(word)) {
                    System.out.println(f);
                }else {
                    if(isContainContent(f, word)) {
                        System.out.println(f);
                    }
                }
            }else {
                scanDir(f, word);
            }
        }
    }
    private static Boolean isContainContent(File f, String word) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        try(InputStream is = new FileInputStream(f)) {
            try(Scanner scanner = new Scanner(is, "UTF-8")) {
                while (scanner.hasNextLine()) {
                    stringBuilder.append(scanner.nextLine());
                    stringBuilder.append("\r\n");
                }
            }
        }
        return stringBuilder.indexOf(word) != -1;
    }
}